import 'axios'
import config from '../common/configs'
import actions from '../index'
import axios from 'axios'
import Qs from 'qs'

const {
    GET_NEWS_SUCCESS,
    GET_NEWS_FAILURE,
    GET_NEWS_UPDATE_SUCCESS,
    GET_NEWS_UPDATE_FAILURE,
    GET_NEWS_DELETE_SUCCESS,
    GET_NEWS_DELETE_FAILURE,
    GET_NEWS_ADD_SUCCESS,
    GET_NEWS_ADD_FAILURE,
} = actions

const baseUrl = config.baseUrl

export function getNews(query=''){
    return async (dispatch) =>{
        try{
            const data = (await axios.get(`${baseUrl}news.do?${Qs.stringify(query)}`)).data
            dispatch({
                type: GET_NEWS_SUCCESS,
                data: data
            })
        }
        catch(e){
            dispatch({
                type: GET_NEWS_FAILURE,
                error: e
            })
        }
    }
}

export function updateNews(query=''){
    return async (dispatch) => {
        try{
            const data = (await axios({
                                        method:'put',
                                        url:`${baseUrl}news.do`,
                                        headers:{"Content-Type":"application/json"},
                                        data:query})).data
            dispatch({
                type: GET_NEWS_UPDATE_SUCCESS,
                data: data,
            })
        }
        catch(e){
            dispatch({
                type: GET_NEWS_UPDATE_FAILURE,
                error: e
            })
        }
    }
}

export function deleteNews(query=''){
    return async (dispatch) =>{
        try{
            const data = (await axios.delete(`${baseUrl}news.do?${Qs.stringify(query)}`)).data
            dispatch({
                type: GET_NEWS_DELETE_SUCCESS,
                data: data
            })
        }
        catch(e){
            dispatch({
                type: GET_NEWS_DELETE_FAILURE,
                error: e
            })
        }
    }
}

export function addNews(query=''){
    return async (dispatch) => {
        try{
            const data = (await axios({
                                        method:'post',
                                        url:`${baseUrl}news.do`,
                                        headers:{"Content-Type":"application/json"},
                                        data:query})).data
            dispatch({
                type: GET_NEWS_ADD_SUCCESS,
                data: data,
            })
        }
        catch(e){
            dispatch({
                type: GET_NEWS_ADD_FAILURE,
                error: e
            })
        }
    }
}
